<script setup>
import {Check, Document} from "@element-plus/icons-vue";
import {computed, reactive, ref} from "vue";
import {Delta, Quill, QuillEditor} from "@vueup/vue-quill";
import ImageResize from "quill-image-resize-vue";
import {ImageExtend, QuillWatch} from "quill-image-super-solution-module";
import '@vueup/vue-quill/dist/vue-quill.snow.css';
import axios from "axios";
import {accessHeader, get, post} from "@/net";
import {ElMessage} from "element-plus";
import ColorDot from "@/components/ColorDot.vue";
import {useStore} from "@/store";

const store = useStore()
const props = defineProps({
    show: Boolean,
    defaultTitle: {
        default: '',
        type: String
    },
    defaultText: {
        default: '',
        type: String
    },
    defaultType: {
        default: null,
        type: Number
    },
    defaultButton: {
        default: '立即发表主题',
        type: String
    },
    submit:{
        default:(editor,success)=>{
            post('/api/forum/create-topic',{
                type:editor.type.id,
                title:editor.title,
                content:editor.text
            },()=>{
                ElMessage.success('帖子发表成功')
                success()

            })
        },type:Function
    }
})
Quill.register('modules/ImageExtend', ImageExtend)
Quill.register('modules/imageResize', ImageResize)
const emit = defineEmits(['close', 'success'])
const editor = reactive({
    type: null,
    title: '',
    text: '',
    loading: false
})
const refEditor = ref()

//重置操作
function initEditor() {
    if (props.defaultText)
        editor.text = new Delta(JSON.parse(props.defaultText))
    else
        refEditor.value.setContents('', 'user')
    editor.title = props.defaultTitle
    editor.type = findTypeById(props.defaultType)
}

//字数统计方法
function deltaToText(delta) {
    if (!delta.ops) return '';
    let str = ""
    for (let op of delta.ops) {
        str += op.insert
    }
    return str.replace(/\s/g, "")
}

const contentLength = computed(() => deltaToText(editor.text).length)

function findTypeById(id) {
    for (let type of store.forum.types)
        if (type.id === id) return type
}

//发表文章
function submitTopic() {
    const text = deltaToText(editor.text)
    if (text.length > 20000) {
        ElMessage.warning("字数超出限制，无法发表")
        return
    }
    if (!editor.type) {
        ElMessage.warning("请选择帖子类型")
        return
    }
    if (!editor.title) {
        ElMessage.warning("请填写标题")
        return
    }
    props.submit(editor,()=>emit('success'))


}


//
const editorOption = {
    modules: {
        toolbar: {
            container: [
                "bold", "italic", "underline", "strike", "clean",
                {color: []}, {'background': []},
                {size: ["small", false, "large", "huge"]},
                {header: [1, 2, 3, 4, 5, 6, false]},
                {list: "ordered"}, {list: "bullet"}, {align: []},
                "blockquote", "code-block", "link", "image",
                {indent: '-1'}, {indent: '+1'}
            ],
            handlers: {
                'image': function () {
                    QuillWatch.emit(this.quill.id)
                }
            }
        }, imageResize: {
            modules: ['Resize', 'DisplaySize']
        }, ImageExtend: {
            action: axios.defaults.baseURL + '/api/image/cache',
            name: 'file',
            size: 5,
            loading: true,
            accept: 'image/png, image/jpeg',
            response: (resp) => {
                if (resp.data) {
                    return axios.defaults.baseURL + '/images' + resp.data
                } else {
                    return null
                }
            },
            methods: 'POST',
            headers: xhr => {
                xhr.setRequestHeader('Authorization', accessHeader().Authorization);
            },
            start: () => editor.uploading = true,
            success: () => {
                ElMessage.success('图片上传成功!')
                editor.uploading = false
            },
            error: () => {
                ElMessage.warning('图片上传失败，请联系管理员!')
                editor.uploading = false
            }
        }
    }
}
</script>

<template>
        <el-drawer :model-value="show" direction="btt"
                   @open="initEditor"
                   :size="650" :close-on-click-modal="false"
                   @close="emit('close')">
            <template #header>
                <div>
                    <div style="font-weight: bold;font-size: 20px;">发表新的帖子</div>
                    <div style="font-size: 13px;">
                        发表内容之前，请遵守相关法律规则，不要骂人等不文明行为，违者封号处理
                    </div>
                </div>
            </template>
            <div>
                <el-card>
                    <div style="display: flex;gap: 10px">
                        <div style="width: 180px">
                            <el-select placeholder="请选择要发布的类型" v-model="editor.type"
                                       :disabled="!store.forum.types.length" value-key="id">
                                <el-option v-for="item in store.forum.types.filter(type=>type.id>0)" :value="item"
                                           :label="item.name">
                                    <div style="display: flex; align-items: center;">
                                        <color-dot :color="item.color"/>
                                        <div :style="{ color: item.color, marginLeft: '15px' }">{{ item.name }}</div>
                                    </div>
                                </el-option>
                            </el-select>
                        </div>
                        <div style="flex: 1">
                            <el-input placeholder="请输入帖子的标题..." :prefix-icon="Document" v-model="editor.title"
                                      style="height: 100%;  --el-input-text-color: #990099;" maxlength="30"
                                      minlength="1"></el-input>
                        </div>
                    </div>

                    <div style="margin-top: 10px;font-size: 15px;font-family: KaiTi;">
                        <color-dot :color="editor.type ? editor.type.color : 'grey'"/>
                        <span style="margin-left: 5px" :style="{ color: editor.type ? editor.type.color : 'grey' }">
                            {{ editor.type ? editor.type.desc : "请在上方选择一个帖子类型" }}</span>
                    </div>
                    <div style="margin-top: 15px;height: 380px;overflow: hidden;border-radius: 10px;"
                         v-loading="editor.uploading" element-loading-text="正在上传图片请稍后">
                        <quill-editor v-model:content="editor.text" style="height: calc(100% - 45px)"
                                      content-type="delta"
                                      placeholder="今天想给大家分享什么！！！！"
                                      ref="refEditor"
                                      :options="editorOption"/>
                    </div>
                    <div style="display: flex;justify-content: space-between;margin-top: 5px">
                        <div style="font-size: 13px;color: grey">
                            当前字数:{{ contentLength }} 最大支持20000
                        </div>
                        <div>
                            <el-button type="success" :icon="Check" @click="submitTopic" plain>{{ defaultButton }}
                            </el-button>
                        </div>
                    </div>
                </el-card>
            </div>
        </el-drawer>
</template>


<style scoped>
:deep(.el-drawer) {
    width: 1100px;
    margin: 20px 10px 50px 400px;
    border-radius: 20px;
}

:deep(.el-drawer__header) {
    margin: 2px;
}

:deep(.ql-editor) {
    font-size: 20px;
    font-family: KaiTi;
    color: #43beec;
}

:deep(.ql-editor.ql-blank::before) {
    color: #43beec;
    font-style: normal;
}

</style>